import operate from '@/utils/operate.js'
const queue = []
export default class Request {
     http(param) {
        // 请求参数
        var url = param.url,
            method = param.method,
            data = param.data || {},
            hideLoading = param.hideLoading || false;

        //拼接完整请求地址
        var requestUrl = operate.api + url;
		var header = {}
        //请求方式:GET或POST(POST需配置
        // header: {'content-type' : "application/x-www-form-urlencoded"},)
        if (method) {
            method = method.toUpperCase(); //小写改为大写
            if (method == "POST") {
                header = {
                    'content-type': "application/x-www-form-urlencoded",
					'token':uni.getStorageSync('token')
                };
            } else {
                header = {
                    'content-type': "application/json",
					'token':uni.getStorageSync('token')
                };
            }
        }

        //加载圈
        if (!hideLoading) {
            // uni.showLoading({
            //     title: '加载中...'
            // });
        }

        // 返回promise
        return new Promise((resolve, reject) => {
			const requestParams = {
			    url: requestUrl,
			    data: data,
			    method: method,
			    header: header,
			    success: (res) => {
			        // 判断 请求api 格式是否正确
			        if (res.statusCode && res.statusCode != 200) {
			            uni.showToast({
			                title: "api错误" + res.errMsg,
			                icon: 'none'
			            });
			            return;
			        }
			        // code判断:200成功,不等于200错误
			        if (res.data.code) {
			            if (res.data.code !== 1) {
							
							if(res.data.code === 401){
								for( let i = 0 ; i < queue.length ; i ++ ){
									queue[i].abort();
								}
								uni.navigateTo({
									url:'/pages/login/index'
								})
								return
							}
							
			                uni.showToast({
			                    title:  res.data.msg,
			                    icon: 'none'
			                });
			                return;
			            }
			        } else {
			            uni.showToast({
			                title: res.data.msg,
			                icon: 'none'
			            });
			            return;
			        }
			        // 将结果抛出
			        resolve(res.data.data)
			    },
			    //请求失败
			    fail: (e) => {
					console.log( e )
			        uni.showToast({
			            title: "" + e.data.msg,
			            icon: 'none'
			        });
			        reject(e.data);
			    },
			    //请求完成
			    complete() {
			        //隐藏加载
			        if (!hideLoading) {
			            uni.hideLoading();
			        }
			        // resolve();
			        return;
			    }
			}
	
            // 请求
            const request = uni.request( requestParams )
			queue.push( request )
        })
    }
	

}